import pymongo
def data_storage(similar_list):
    print('正在插入mongo')
    new_similar_list = []
    for i in similar_list:
        new_similar_list.append({
            "datasetA": i.datasetA.id,
            "datasetB": i.datasetB.id,
            "EuclideanDistance": i.EuclideanDistance
        })
    new_similar_list

    dict_new_similar_list = {}

    for i in new_similar_list:
        dict_new_similar_list.setdefault(i.get("datasetB"), []).append(i)

    recommend_list = []
    for key, value in dict_new_similar_list.items():
        value.sort(key=lambda x:x['EuclideanDistance'], reverse=True)
        if len(value) < 3:
            recommend_list.append({
                f"{key}": {"recommend":[i["datasetA"] for i in value]}
            })
        else:
            recommend_list.append({
                f"{key}": {"recommend":[value[0]["datasetA"], value[1]["datasetA"], value[2]["datasetA"]]}
            })

    client = pymongo.MongoClient('mongodb://mongodb:27017/')
    db = client["Cache"]
    collection = db['cache']

    for i in recommend_list:
        collection.update_one({
            'id': f'{list(i.keys())[0]}'
        },{
            '$set':{
                'recommend': i[f"{list(i.keys())[0]}"]["recommend"]
            }
        })

    print('结束')